package cn.sofwin.orm;

import cn.sofwin.orm.entity.Article;
import cn.sofwin.orm.mapper.ArticleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

@Slf4j
public class Main {
    public static void main(String[] args) {
        // 1.指定配置文件路径
        String resource = "mybatis-config.xml";
        SqlSessionFactory sqlSessionFactory = null;
        SqlSession session = null;
        try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
            // 2.从 XML 中构建 SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 3.从 SqlSessionFactory 中获取 SqlSession
            session = sqlSessionFactory.openSession();

            // 4.执行查询
            ArticleMapper articleMapper =  session.getMapper(ArticleMapper.class);
            Article article = articleMapper.selectOne(12);
            log.warn("文章信息：{}", article);
            System.out.println("===================");
            List<Article> list=articleMapper.selectAll();
            log.warn("所有文章：{}",list );

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(session != null){
                session.close();
            }
        }
    }
}
